package com.loie.datacenter.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.loie.datacenter.comm.CommJSON;
import com.loie.datacenter.comm.ExcelConst;
import com.loie.datacenter.model.bo.*;
import com.loie.datacenter.service.FinanceService;
import com.loie.datacenter.service.UserListService;
import com.loie.datacenter.util.ExcelUtil;
import com.loie.datacenter.util.SecureUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhl
 * @create 2021/9/11 19:55
 */
@Slf4j
@RequestMapping("/financial")
@RestController
@AllArgsConstructor
public class FinanceController {

    private final FinanceService financeService;
    private final RedisTemplate<String, String> redisTemplate;
    private final UserListService userListService;


    @PostMapping("/getFinancialList")
    public
    CommJSON getFinancialList(@RequestBody String msg, @CurrentUser TokenInfoBO tokenInfoBO) {
        CommJSON commJson = new CommJSON();
        try {
            String aesSecureKey = redisTemplate.opsForValue().get(SecureUtil.MD5Encode(String.format("[DataCenter][secretKey][%s]",
                    tokenInfoBO.getToken())));
            String mwMsg = SecureUtil.decryptAES(msg, aesSecureKey);
            FinanceBO bo = JSONObject.parseObject(mwMsg, FinanceBO.class);

            List<FinanceBO> dataList = financeService.getFinanceList(bo, tokenInfoBO.getUser());
            FinanceSumBO financeSumBO = financeService.getFinanceCount(bo, tokenInfoBO.getUser());
            String accountReceivableSum = financeSumBO.getAccountReceivableSum();
            String receivedAccountSum = financeSumBO.getReceivedAccountSum();
            String remainAccountSum = financeSumBO.getRemainAccountSum();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("total", financeSumBO.getTotal());
            jsonObject.put("payableSum", accountReceivableSum == null ? 0 : accountReceivableSum);
            jsonObject.put("paidSum", receivedAccountSum == null ? 0 : receivedAccountSum);
            jsonObject.put("unpaidSum", remainAccountSum == null ? 0 : remainAccountSum);
            jsonObject.put("list", dataList);

            commJson.setSuccess(true);
            commJson.setData(SecureUtil.encryptAES(jsonObject.toJSONString(), aesSecureKey));
        } catch (Exception e) {
            commJson.setErrorMessage("Sorry, Query exception(code:1201)");
            commJson.setError();
            e.printStackTrace();
            log.error("FinanceController.getFinancialList()===>", e);
        }
        return commJson;
    }

    /**
     * 导出参加信息表
     *
     * @param res
     * @throws Exception
     */
    @PostMapping(value = "/downloadFinancialList")
    public void downloadTaskInfo(@RequestBody String msg, @CurrentUser TokenInfoBO tokenInfoBO, HttpServletResponse res) throws Exception {
        try {
            String aesSecureKey = redisTemplate.opsForValue().get(SecureUtil.MD5Encode(String.format("[DataCenter][secretKey][%s]",
                    tokenInfoBO.getToken())));

            UserListBO userListBO = userListService.getUserInfoByUser(tokenInfoBO.getUser());
            String mwMsg = SecureUtil.decryptAES(msg, aesSecureKey);
            FinanceBO bo = JSONObject.parseObject(mwMsg, FinanceBO.class);
            bo.setPageIndex(-1);
            List<FinanceBO> dataList = financeService.getFinanceList(bo, tokenInfoBO.getUser());
            List<JSONObject> headList = new ArrayList<>();
            int authority = userListBO.getDataAuthority();

            List<List<String>> lists = new ArrayList<>();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Invoice NO.");
            jsonObject.put(ExcelConst.WIDTH, 3500);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "PO NO.");
            jsonObject.put(ExcelConst.WIDTH, 3500);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);

            if (authority == 2) {
                jsonObject = new JSONObject();
                jsonObject.put(ExcelConst.TITLE, "Customer Name");
                jsonObject.put(ExcelConst.WIDTH, 5000);
                jsonObject.put(ExcelConst.TYPE, "1");
                headList.add(jsonObject);
            }
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "ETD");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);

            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Trade Term");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
//            jsonObject = new JSONObject();
//            jsonObject.put(ExcelConst.TITLE, "POL");
//            jsonObject.put(ExcelConst.WIDTH, 3000);
//            jsonObject.put(ExcelConst.TYPE, "1");
//            headList.add(jsonObject);
//            jsonObject = new JSONObject();
//            jsonObject.put(ExcelConst.TITLE, "POD");
//            jsonObject.put(ExcelConst.WIDTH, 3000);
//            jsonObject.put(ExcelConst.TYPE, "1");
//            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Payment Term");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Due Date");
            jsonObject.put(ExcelConst.WIDTH, 3000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Currency");
            jsonObject.put(ExcelConst.WIDTH, 2000);
            jsonObject.put(ExcelConst.TYPE, "1");
            headList.add(jsonObject);

            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Payable");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0.00");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Paid");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0.00");
            headList.add(jsonObject);
            jsonObject = new JSONObject();
            jsonObject.put(ExcelConst.TITLE, "Unpaid");
            jsonObject.put(ExcelConst.WIDTH, 4000);
            jsonObject.put(ExcelConst.TYPE, "2");
            jsonObject.put(ExcelConst.FORMAT, "#,#0.00");
            headList.add(jsonObject);

            for (int i = 0; i < dataList.size(); i++) {
                List<String> list = new ArrayList<>();
                list.add(dataList.get(i).getInvoiceNO());
                list.add(dataList.get(i).getCustomerContractNo());
                if (authority == 2) {
                    list.add(dataList.get(i).getCustomerCorpName());
                }
                list.add(dataList.get(i).getShippingDate());
                list.add(dataList.get(i).getTermOfPrice());
                list.add(dataList.get(i).getPayment());
                list.add(dataList.get(i).getCollectionDate());
                list.add(dataList.get(i).getCurrency());
                list.add(dataList.get(i).getAccountReceivable());
                list.add(dataList.get(i).getReceivedAccount());
                list.add(dataList.get(i).getRemainAccount());

                lists.add(list);
            }
            ExcelUtil.getExcel(res, lists, headList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("FinanceController.downloadTaskInfo()===>", e);
        }
    }
}
